package cn.xm.org.service.impl;

import cn.xm.basic.config.BussinessException;
import cn.xm.basic.query.BaseQuery;
import cn.xm.basic.util.BaiduAuditUtils;
import cn.xm.basic.util.PageList;
import cn.xm.org.domain.Employee;
import cn.xm.org.domain.Shop;
import cn.xm.org.domain.ShopAuditLog;
import cn.xm.org.enu.ShopStateEnum;
import cn.xm.org.mapper.EmployeeMapper;
import cn.xm.org.mapper.ShopMapper;
import cn.xm.org.service.ShopAuditLogService;
import cn.xm.org.service.ShopService;
import cn.xm.basic.service.impl.BaseServiceImpl;
import cn.xm.org.vo.ShopEchartsVo;
import net.bytebuddy.implementation.bytecode.Throw;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xm
 * @since 2022-10-15
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements ShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopService shopService;
    @Autowired
    private ShopAuditLogService shopAuditLogService;
    // 邮件核心对象
    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void settlement(Shop shop) {
        Employee admin = shop.getAdmin();
        Employee employee = this.verify(shop);
        shopMapper.add(shop);
        if (employee == null) {
            employeeMapper.add(admin);
        }
        admin.setShopId(shop.getId());
        employeeMapper.update(admin);
        shop.setAdminId(admin.getId());
        shopMapper.update(shop);

    }

    @Override
    public void auditPass(ShopAuditLog shopAuditLog) throws MessagingException {
        // 改变店铺的状态
        Shop shop = new Shop();
        shop.setId(shopAuditLog.getAuditId());
        shop.setState(2);
        shopService.update(shop);
        // 保存日志
        shopAuditLog.setAuditId(311L);
        shopAuditLogService.add(shopAuditLog);
        // 发送邮件
        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 2.发送复杂邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("775366739@qq.com");
        helper.setSubject("宠物之家审核通知");
        // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
        helper.setText("<h1>恭喜你通过宠物之家审核</h1>"+
                "http://localhost:8080/shop/active/"+shopAuditLog.getShopId(),true);
        // 5.设置收件人
        helper.setTo("775366739@qq.com");
        // 6.发送邮件
        javaMailSender.send(mimeMessage);

    }

    @Override
    public void active(Long id) {
        Shop shop = new Shop();
        shop.setId(id);
        shop.setState(2);
        shopService.update(shop);

    }

    @Override
    public void auditReject(ShopAuditLog shopAuditLog) throws MessagingException {
        // 改变店铺状态为驳回
        Shop shop = new Shop();
        shop.setState(-1);
        shop.setId(shopAuditLog.getShopId());
        shopService.update(shop);
        // 保存日志
        shopAuditLog.setAuditId(311L);
        shopAuditLogService.add(shopAuditLog);
        // 发送邮件
        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        // 2.发送复杂邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("775366739@qq.com");
        helper.setSubject("宠物之家审核通知");
        // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
        helper.setText("<h1>您填写的信息有误,请点击连接重填：</h1>"+shopAuditLog.getNote()+"/r/n"+
                "http://localhost:8081/#/registerAgain?shopId="+shopAuditLog.getShopId(),true);
        // 5.设置收件人
        helper.setTo("775366739@qq.com");
        // 6.发送邮件
        javaMailSender.send(mimeMessage);
    }

    @Override
    public Map<String,Object> echarts() {
        List<ShopEchartsVo> shopEchartsVos = shopMapper.echarts();
        List<Integer> states = shopEchartsVos.stream().map(ShopEchartsVo::getState).collect(Collectors.toList());
        List<Integer> count = shopEchartsVos.stream().map(ShopEchartsVo::getCount).collect(Collectors.toList());
        ArrayList<String> names = new ArrayList<>();
        for(Integer state:states) {
            String nameByCode = ShopStateEnum.getNameByCode(state);
            names.add(nameByCode);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("x",names);
        map.put("y",count);
        return map;
    }

    public Employee verify(Shop shop) {
        if (StringUtils.isBlank(shop.getName())) {
            throw new BussinessException("店铺名字不能为空");
        }
        if (!BaiduAuditUtils.TextCensor(shop.getName())) {
            throw new BussinessException("请输入合法的字符");
        }
        if (!BaiduAuditUtils.ImgCensor(shop.getLogo())) {
            throw new BussinessException("请输入合法的图片");
        }
        if (StringUtils.isBlank(shop.getTel())) {
            throw new BussinessException("座机不能为空");
        }
        if (StringUtils.isBlank(shop.getTel())) {
            throw new BussinessException("店铺地址不能为空");
        }
        Shop shopByName = shopMapper.findByName(shop.getName());
        if (shopByName != null) {
            throw new BussinessException("店铺已存在");
        }
        Employee admin = shop.getAdmin();
        if (admin.getPassword().equals(admin.getConfirmPassord())) {
            throw new BussinessException("两次密码不一致");
        }
        Employee employee = employeeMapper.findByName(admin.getUsername());
        if (employee != null && employee.getShopId() != null) {
            Shop shop2 = shopMapper.findById(employee.getShopId());
            if (shop2.getAdminId() == employee.getId()) {
                throw new BussinessException("该管理员已经管理了其他店铺！");
            }
        }
        return employee;
    }

    @Override
    public PageList<Shop> queryByPage(BaseQuery query) {
        // 分页查询店铺，带有管理员字段的值
        PageList<Shop> shopPageList = super.queryByPage(query);
        // 取出各个店铺的id作为一个集合
        List<Shop> rows = shopPageList.getRows();
        List<Long> ids = rows.stream().map(Shop::getId).collect(Collectors.toList());
        // 店铺的id作为日志的shopId查出所有的日志
        List<ShopAuditLog> shopAuditLogs = shopAuditLogService.findByShopId(ids);
        // 按shopId分组将日志放在一个map中
        Map<Long, List<ShopAuditLog>> auditMap = shopAuditLogs.stream().collect(Collectors.groupingBy(ShopAuditLog::getShopId));
        //
        rows.forEach(shop -> {
            shop.setShopAuditLogs(auditMap.get(shop.getId()));
        });
        return shopPageList;
    }
}
